﻿using Newtonsoft.Json;
using Serilog;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading.Tasks;
using xhim.common.Exceptions;
using xhim.common.Helper;

namespace xhim.common.Api
{
    public static class ApiHelper
    {
        private const string GET_METHOD = "GET";
        private const string POST_METHOD = "POST";

        private static HttpHelper _httpHelper = new HttpHelper();
        static ApiHelper()
        {
        }
        public static ApiResultModel doGet(string url)
        {
            return doRequest(url, GET_METHOD);
        }
        public static ApiResultModel doGet(string url, Dictionary<string, object> headers)
        {
            return doRequest(url, GET_METHOD, headers);
        }

        public static ApiResultModel doPost(string url)
        {
            return doRequest(url, POST_METHOD);
        }
        public static ApiResultModel doPost(string url, Dictionary<string, object> headers)
        {
            return doRequest(url, POST_METHOD, headers);
        }
        public static ApiResultModel doPost(string url, Dictionary<string, object> headers, object data)
        {
            return doRequest(url, POST_METHOD, headers, data);
        }
        private static ApiResultModel doRequest(string url, string method)
        {
            return doRequest(url, method, null);
        }

        private static ApiResultModel doRequest(string url, string method, Dictionary<string, object> headers)
        {
            return doRequest(url, method, headers, null);
        }

        private static ApiResultModel doRequest(string url, string method, Dictionary<string, object> headers, object data)
        {
            return doRequest(url, method, headers, data, "application/json");
        }

        private static ApiResultModel doRequest(string url, string method, Dictionary<string, object> headers, object data, string contentType)
        {
            //Debug.WriteLine("\n>>> doRequest [{1}]{0} \nHeader:{2}\nBody:{3}", url, method, JsonConvert.SerializeObject(headers), JsonConvert.SerializeObject(data));
            Log.Debug(">>> doRequest [{method}] {url} \nHeader:{@headers}\nBody:{@data}", method, url, headers, data);
            HttpItem item = new HttpItem()
            {
                URL = url,
                Method = method,
                ContentType = contentType,

                Encoding = Encoding.UTF8,
                Timeout = 60000,
                ReadWriteTimeout = 30000,
                IsToLower = false,

                UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
                Accept = "application/json, text/plain, */*",
                KeepAlive = true,
            };
            if (headers != null)
            {
                foreach (string key in headers.Keys)
                {
                    item.Header.Add(key, headers[key].ToString());
                }
            }
            if (data != null)
            {
                item.Postdata = JsonConvert.SerializeObject(data);
            }
            ApiResultModel resultModel = new ApiResultModel();


            HttpResult httpResult = _httpHelper.GetHtml(item);
            if (httpResult == null)
            {
                Log.Warning("*** ApiException [{url}] \nHeader:{@headers}\nBody:{@data}", url, headers, data);
                throw new ApiException(ApiResultModel.Fail("API请求异常"));

            }
            //Log.Debug("\n<<< doRequest Response: {@httpResult}", httpResult);

            if (httpResult.StatusCode == System.Net.HttpStatusCode.OK)
            {

                string result = httpResult.Html;
                if (result is null)
                {
                    return ApiResultModel.Success();
                }

                resultModel = JsonConvert.DeserializeObject<ApiResultModel>(result);
                Log.Debug("<<< ApiResultModel: {url}\n{@result}", url, result);
                //Debug.WriteLine(JsonConvert.SerializeObject(resultModel));
                if (resultModel != null && resultModel.isSuccess)
                {
                    return resultModel;
                }
                else
                {
                    Log.Warning("*** ApiException [{url}] \nHeader:{@headers}\nBody:{@data}\nResult:{@httpResult}", url, headers, data, resultModel);
                    throw new ApiException(resultModel);
                }
            }
            else
            {
                Log.Warning("*** ApiException [{url}] \nHeader:{@headers}\nBody:{@data}\nException:{@httpResult}", url, headers, data, httpResult);
                throw new ApiException(ApiResultModel.Fail(ApiResultModel.ERROR, "API请求异常", httpResult.StatusCode.ToString(), httpResult.Html));
            }

        }

    }
}
